<template>
	<div class="shortUrl login">
		<el-form  label-width="100px" class="demo-ruleForm">
			<el-form-item>
				<span>原网址</span>
				<el-input
					ref='url'
					type="textarea"
					placeholder="请输入网址"
					v-model="url"
					maxlength="500"
					show-word-limit
					:autosize="{ minRows:4 , maxRows: 6}">
				</el-input>
			</el-form-item>
			<el-form-item v-show='user'>
				<span>备<i class='marginOne'></i>注</span>
				<el-input
					type="textarea"
					placeholder="请填写备注"
					v-model="note"
					maxlength="30"
					show-word-limit
					:autosize="{ minRows: 2, maxRows: 3}">
				</el-input>
			</el-form-item>
			<el-form-item>
				<span>短网址</span>
				<el-input v-model="shortUrl" readonly @click.native='copyText($event)'></el-input>
			</el-form-item>
		</el-form>
		<div class="bottom"> 
			<p>
				<el-link v-if='user' type="success" @click="$router.push('/userCenter/shortUrl')">我的短网址</el-link>
			</p>
			<el-button  type="primary" @click="generate">生 成</el-button>
			<el-button @click="$emit('closeDialog')">取 消</el-button>
		</div>
	</div>
</template>
<script>
	import {generateUrl,api} from '@/api/public'
	export default{
		name:'shortUrl',
		data(){
			return{
				url:'',
				note:'',
				shortUrl:'',
				user:sessionStorage.getItem('token')
			}
		},
		methods:{
			copyText(This){
				if(this.shortUrl){
					This.target.select();
	      			document.execCommand("Copy");
	      			this.info('短网址复制成功');
				}
	      	},
			async generate(){
				if(!this.url) return this.info('原网址不能为空','w');
				let reg=/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;
				let isWebSite=reg.test(this.url);
				if(!isWebSite){this.$refs.url.focus();return this.info('输入的不是一个网址','w');}
				let {code,ae_url}=await generateUrl(this.url);
				if(code===1){
					if(this.user){
						let {success}=await api('post','website',-1,{url:this.url,shortUrl:ae_url,note:this.note})
						if(!success)  return this.info('短网址生成失败','e');
					}
					this.shortUrl=ae_url;
					this.url=this.note='';
					this.info('短网址生成成功');
					let routePath=this.$route.path;
					if(routePath=='/userCenter/shortUrl') this.$emit('getData');
				}
				else this.info('短网址生成失败','e');
			}
		}
	}
</script>
<style lang='stylus' scoped>
	.shortUrl{
		max-width: 550px;
   		margin: 0 auto;
		>>>.el-form-item__content{
			display:flex;
			>span{
				width: 72px;
    			margin-left: 1.2em;
				font-size:16px;
			}
			>.el-textarea,>.el-input{
				width:79%;
			}
		}
	}
</style>